import { app, BrowserWindow, shell } from 'electron'
import { join, dirname } from 'node:path'
import { fileURLToPath } from 'node:url'
import { existsSync } from 'node:fs'

const VITE_DEV_SERVER_URL = process.env.VITE_DEV_SERVER_URL

// __dirname is not available in ESM; reconstruct it for Electron main process
const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

// 允许渲染进程访问本地文件资源（开发阶段）
// 解决 Chromium "Not allowed to load local resource" 报错
app.commandLine.appendSwitch('allow-file-access-from-files')

function createMainWindow() {
  const mainWindow = new BrowserWindow({
    width: 1100,
    height: 720,
    show: false,
    webPreferences: {
      contextIsolation: true,
      nodeIntegration: false,
      // 关闭同源策略 & 允许 HTTP 页面请求本地 file:// 资源（开发阶段）
      webSecurity: false,
      allowRunningInsecureContent: true,
      preload: join(__dirname, 'preload.mjs'),
    },
  })

  mainWindow.once('ready-to-show', () => mainWindow.show())

  mainWindow.webContents.setWindowOpenHandler(({ url }) => {
    shell.openExternal(url)
    return { action: 'deny' }
  })

  if (VITE_DEV_SERVER_URL) {
    mainWindow.loadURL(VITE_DEV_SERVER_URL)
    mainWindow.webContents.openDevTools({ mode: 'detach' })
  } else {
    // 生产环境：从 app.asar 或 dist 目录加载
    // app.asar 内部路径：dist-electron/../dist/index.html
    // 解压后路径结构：resources/app.asar 包含整个项目
    const possibleIndex = [
      join(__dirname, '../dist/index.html'),  // asar 内或开发环境
      join(process.resourcesPath, 'app.asar/dist/index.html'), // 备用
    ]
    const indexFile = possibleIndex.find(p => existsSync(p))
    if (indexFile) {
      mainWindow.loadFile(indexFile)
    } else {
      console.error('无法找到 index.html，尝试的路径：', possibleIndex)
    }
  }
}

app.whenReady().then(() => {
  createMainWindow()

  app.on('activate', () => {
    if (BrowserWindow.getAllWindows().length === 0) createMainWindow()
  })
})

app.on('window-all-closed', () => {
  if (process.platform !== 'darwin') app.quit()
})


